<script setup lang="ts">
import { Button, Card } from 'ant-design-vue';
import { onMounted, ref } from 'vue';
// import { useRouter } from 'vue-router';
import { fetchOnlineNodes } from '@/service/api/node';
import { useTableScroll } from '@/hooks/common/table';
import { $t } from '@/locales';
import { useRouterPush } from '@/hooks/common/router';
const { routerPushByKey } = useRouterPush();
const { tableWrapperRef, scrollConfig } = useTableScroll();

const loading = ref(false);
const data = ref<any[]>([]);

// const router = useRouter();

const columns = [
  {
    key: 'index',
    title: $t('common.index'),
    dataIndex: 'index',
    align: 'center' as const,
    width: 64
  },
  {
    key: 'ip',
    title: 'IP地址',
    dataIndex: 'ip',
    align: 'center' as const,
    minWidth: 120
  },
  {
    key: 'port',
    title: '端口',
    dataIndex: 'port',
    align: 'center' as const,
    minWidth: 80
  },
  {
    key: 'cpu',
    title: 'CPU使用率',
    dataIndex: 'cpu',
    align: 'center' as const,
    minWidth: 100
  },
  {
    key: 'memory',
    title: '内存使用量',
    dataIndex: 'memory',
    align: 'center' as const,
    minWidth: 120
  },
  {
    key: 'status',
    title: '在线状态',
    dataIndex: 'status',
    align: 'center' as const,
    width: 100
  },
  {
    key: 'actions',
    title: '操作',
    align: 'center' as const,
    width: 100
  }
];

async function getData() {
  loading.value = true;
  try {
    const res = await fetchOnlineNodes();
    // console.info('fetchOnlineNodes 返回：', res);

    // 处理返回的数据
    let records = res.data || [];

    // 处理 raw 数据
    records = records.map((item: any) => {
      if (item.raw) {
        try {
          const obj: Record<string, string> = {};
          item.raw
            .replace(/\{|\}/g, '')
            .split(',')
            .forEach((pair: string) => {
              const [k, v] = pair.split('=');
              if (k && v) {
                obj[k.trim()] = v.trim();
              }
            });
          return {
            ip: obj.ip || item.ip,
            port: obj.port || item.port,
            cpu: obj.cpu || item.cpu,
            memory: obj.memory || item.memory,
            status: item.status || 'online'
          };
        } catch {
          return item;
        }
      }
      return {
        ip: item.ip,
        port: item.port,
        cpu: item.cpu,
        memory: item.memory,
        status: item.status || 'online'
      };
    });

    // console.info('处理后的 records：', records);

    // 添加索引
    data.value = records.map((item, index) => ({
      ...item,
      index: index + 1
    }));
  } catch (error) {
    console.error('获取节点列表失败：', error);
    data.value = [];
  } finally {
    loading.value = false;
  }
}

function refresh() {
  getData();
}

function goToDetail(record: any) {
  routerPushByKey('tenant_node-detail', { query: { ip: record.ip, port: record.port } });
}

onMounted(() => {
  getData();
});
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <Card
      title="计算节点管理"
      :bordered="false"
      :body-style="{ flex: 1, overflow: 'hidden' }"
      class="flex-col-stretch sm:flex-1-hidden card-wrapper"
    >
      <template #extra>
        <Button type="primary" :loading="loading" @click="refresh">刷新</Button>
      </template>
      <ATable
        ref="tableWrapperRef"
        :columns="columns"
        :data-source="data"
        size="small"
        :scroll="scrollConfig"
        :loading="loading"
        :row-key="(item: any) => `${item.ip}:${item.port}`"
        :pagination="false"
        class="h-full"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <ATag :color="record.status === 'online' ? 'success' : 'error'">
              {{ record.status === 'online' ? '在线' : '离线' }}
            </ATag>
          </template>
          <template v-if="column.key === 'actions'">
            <Button type="link" size="small" @click="goToDetail(record)">详情</Button>
          </template>
        </template>
      </ATable>
    </Card>
  </div>
</template>
